while loop


Published on: July 03, 2021 By T.Andrew Rayan

while loop:

The while loop is used to execute the block of code until the mentioned condition is true.

Syntax for while loop:

while(condition){
  // block of codes
}

Example for while loop:

This will print the value from 1 to 10 to the console. In the above program we have initialized the value for i as 1 and check the condition in while loop whether the value of i is less than or equal to 10. Also we will increment the value of i inside the while loop.

In real world we use the while loop for dynamic value or condition change and not like above scenario.

do/while loop:

The do-while loop, works in the same way as the while loop but here we the block of codes are executed atleast once even if the condition is not satisfied.

Syntax for do/while loop:

do {
	// Block of codes.
} while(condition);

Here the block inside the do/while loop is executed initially with no condition check and from the next iteration of the loop we will check the condition in the while loop.

Example for do/while loop:

Output:

11

In the above code we have initialized the value of i to be 11. Then it enters the do/while loop with no condition check initially and prints the value 11. Then it increments the value of i.

Now in the next iteration it checks whether the value of i is less than or equal to 10. But the value of i is now 12 so it will not enter the block of codes any further.


Most Read